package com.museum.service.impl.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.museum.base.BaseApiService;
import com.museum.base.BaseResponse;

import com.museum.core.utils.RedisUtil;
import com.museum.entity.DO.Area;
import com.museum.entity.DO.Token;
import com.museum.entity.DO.User;
import com.museum.entity.DO.UserRole;

import com.museum.entity.DTO.admin.AdminQueryUser;
import com.museum.entity.DTO.role.UserRoleDTO;
import com.museum.entity.DTO.user.UserAdd;
import com.museum.entity.DTO.user.UserAll;

import com.museum.mapper.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LB
 * @version 1.0
 * @date 2020/12/21 11:26
 */
@Service
public class AdminUserServiceImpl extends BaseApiService<JSONObject> {
    public static final Object lock = 1;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AreaPermissionMapper apMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private TokenMapper tokenMapper;
    @Autowired
    private RoleMapper roleMapper;

    public BaseResponse<JSONObject> getAllUser(long current, long limit, AdminQueryUser userQuery) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", (current - 1) * limit);
        params.put("size", limit);
        String AreaName = null;
        String UserName = null;
        String realName = null;
        if (userQuery != null) {
            UserName = userQuery.getUserName();
            AreaName = userQuery.getAreaName();
            realName = userQuery.getRealName();
        }
        if (!StringUtils.isEmpty(UserName)) {
            params.put("userName", '%' + UserName + '%');
        }
        if (!StringUtils.isEmpty(AreaName)) {
            params.put("AreaName", '%' + AreaName + '%');
        }
        if (!StringUtils.isEmpty(realName)) {
            params.put("realName", '%' + realName + '%');
        }
        List<User> users = userMapper.selectUserAdmin(params);
        List<UserAll> userAllList = new ArrayList<>();
        for (User user : users) {
            UserAll userAll = new UserAll();
            BeanUtils.copyProperties(user, userAll);
            //获得每个用户的角色
            Integer id = user.getUserId();
            Integer role_id = userRoleMapper.selectRoleIdByUserId(id);
            //根据用户的id 查出用户的地域名字
            Integer areaNumber = user.getAreaNumber();
            String areaName = areaMapper.selectNameByNumber(areaNumber);
            userAll.setAreaName(areaName);
            //根据role_id查询用户的角色
            String role_Name = roleMapper.getRoleNameByRoleId(role_id);
            UserRoleDTO userRole = new UserRoleDTO();
            userRole.setRoleId(role_id);
            userRole.setRoleName(role_Name);
            userAll.setUserRole(userRole);
            userAllList.add(userAll);
        }
        //现在是有了地域号码
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", userMapper.selectCount(null));
        jsonObject.put("userList", userAllList);
        return setResultSuccess(jsonObject);
    }

    public BaseResponse<JSONObject> deleteId(HttpServletRequest request, Integer userId) {
        int count = userMapper.selectCount(new QueryWrapper<User>().eq("user_id", userId));
        if (count <= 0) {
            return setResultError("删除失败,无此人员");
        }
        //删除用户
        int delete = userMapper.delete(new QueryWrapper<User>().eq("user_id", userId));
        if (delete == 1) {
            userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
            //更新用户的状态 将该用户的token置为1
            Token oldToken = tokenMapper.selectOne(new QueryWrapper<Token>().eq("userId", userId).eq("isAvailability", 0));
            if (oldToken != null) {
                oldToken.setIsAvailability(1);
                tokenMapper.updateById(oldToken);
                String OtherToken = oldToken.getToken();
                String flag = redisUtil.getString(OtherToken);
                if (!StringUtils.isEmpty(flag)) {
                    redisUtil.delKey(OtherToken);
                }
            }
        } else {
            return setResultError("系统错误,删除失败");
        }
        //删除用户对应的角色
        return setResultSuccess("删除成功");
    }


    public BaseResponse<JSONObject> AddUser(HttpServletRequest request, UserAdd userAdd) {
        synchronized (this) {
            //地域的编号
            if (userAdd.getAreaNumber() == null) {
                return setResultError("请添加地域");
            }
            Integer areaNumber = userAdd.getAreaNumber();
            int count = areaMapper.selectCountByNumber(areaNumber);
            if (count <= 0) {
                return setResultError("请添加正确的地域信息");
            }
            String userName = userAdd.getUserName();
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", userName));
            if (user != null) {
                return setResultError(202, "该账号已经存在");
            }
            User user2 = new User();
            BeanUtils.copyProperties(userAdd, user2);
            user2.setAreaNumber(areaNumber);
            user2.setUserStatus(0);
            Integer roleId = userAdd.getRoleId();
            UserRole userRole = new UserRole();
            //查询一个地域下面所有角色id
            List<Integer> roleIds = roleMapper.selectRoleIdsByAreaId(areaNumber);
            if (StringUtils.isEmpty(roleId) || roleId == 0) {
                userMapper.insert(user2);
                userRole.setRoleId(200);
                userRole.setUserId(user2.getUserId());
                userRoleMapper.insert(userRole);
            } else {
                //前端传入了对应的角色 分配对应的角色
                if (roleIds.contains(roleId)) {
                    userMapper.insert(user2);

                    userRole.setRoleId(roleId);
                    userRole.setUserId(user2.getUserId());
                    userRoleMapper.insert(userRole);
                } else {
                    return setResultError("该地区无此角色");
                }
            }
        }
        return setResultSuccess(200, "添加成功");
    }


    public BaseResponse<JSONObject> updateUser(UserAdd user) {
        //判断地域
        if (StringUtils.isEmpty(user.getAreaNumber()) || user.getAreaNumber() == 0) {
            return setResultError("地域不能为空");
        }
        //查询是否有此地域
        int count = areaMapper.selectCount(new QueryWrapper<Area>().eq("area_number", user.getAreaNumber()));
        if (count <= 0) {
            return setResultError("无此地域");
        }
        if (StringUtils.isEmpty(user.getRoleId()) || user.getRoleId() == 0) {
            return setResultError("角色不能为空");
        }
        Integer roleId = user.getRoleId();
        int roleFlag = 0;
        Integer userId = user.getUserId();
        //根据用户userId 拿到roleId 根据roleId 判断level是不是0
        int level = roleMapper.getLevelByRoleId(roleId);
        if (level == 0) {
            //默认角色 level=0
            roleFlag = 1;
        }
        if (roleFlag == 0) {
            //判断选择的角色 在该地域是否存在
            int flag = roleMapper.selectCountByArea(roleId, user.getAreaNumber());
            if (flag <= 0) {
                return setResultError("该地区无此角色");
            } else {
                userRoleMapper.updateByUserId(user.getUserId(), roleId);
            }
        } else {
            userRoleMapper.updateByUserId(user.getUserId(), roleId);
        }
        String userName = user.getUserName();
        User user2 = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", userName).ne("user_id", userId));
        if (user2 != null && user2.getUserName().equals(user.getUserName())) {
            return setResultError(202, "该账户已经存在");
        }
        User userEnd = new User();
        BeanUtils.copyProperties(user, userEnd);
        System.out.println("修改的角色=" + userEnd);
        int i = userMapper.updateById(userEnd);
        if (i > 0) {
            return setResultSuccess(200, "修改成功");
        } else {
            return setResultError(202, "修改失败");
        }
    }
}

